<?php
namespace app\admin\controller;
use think\Request;
use think\Db;
use app\common\controller\Init;

class ApiCloudAdmin extends Init
{
	protected $beforeActionList = ['start'];
    public function start()
    {
    	if (!Request::instance()->isPost()) {
            header('Content-type: application/json');  
            exit(json_encode(array('code' => -1 ,'msg' => '非法请求'),true));
        }
    }
    
    public function login()
    {
      	$data = Request::instance()->post();
     	$time = $data['request-time'];
    	if (!$this->keyInfo['token']) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>-1, 'msg'=>'请配置接口参数']));
    	}
        if (empty($data['request-token']) || empty($time)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>-1, 'msg'=>'缺少请求的必要参数']));
        }
        if (((time() - 3600) > $time) || ((time() + 3600) < $time)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>-1, 'msg'=>'请求超时']));
        }
        if ($data['request-token'] != md5($time . md5($this->keyInfo['token']))) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>-1, 'msg'=>'TOKEN错误']));
        }
        if (!isset($data['username']) || !$data['username']) {
            return jsonError('请输入用户名');
        }
    	$userInfo = db('BaseAdmin')->where('username',$data['username'])->find();
        if (!$userInfo) {
            return jsonError('账号不存在');
        }
        if($userInfo['status'] == 1) {
            return jsonError('你的账号被禁止登录');
        }
        db('BaseAdmin')->where('uid',$userInfo['uid'])->update(array(
            'last_login_time' => time(),
            'last_login_ip' => Request::instance()->ip(),
            'login_num' => $userInfo['login_num'] + 1,
        ));
        $userInfo['password'] = null;
        $userInfo['salt'] = null;
        $token = unid();
        db('BaseAdminToken')->insert(array('uid' => $userInfo['uid'],'add_time' => time(),'token' => $token));
        cookie('adminToken',$token,360000);
        model('app\common\model\Log')->itemAdd('登录成功，登录IP：' . Request::instance()->ip(),$userInfo['uid'],'adminLogin');
     	$this->redirect(config('domain') . '/' . config('admin') . '/',302);
    }
    
}
